package com.kehongborui.fliggy.interceptor;

import com.kehongborui.fliggy.enums.LOGIN_USER;
import com.kehongborui.fliggy.exception.AuthenticationException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.kehongborui.fliggy.enums.ExceptionMessage.USER_NOT_LOGIN;

/**
 * 检查用户登陆
 *
 * @author zhang peng yang ming
 * @create 2018-08-30 23:00
 */
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果用户为空
        if (request.getSession().getAttribute(LOGIN_USER.USER.name()) == null) {
            // 获取X-Requested-With信息，判断用户是否是异步请求
            String requestType = request.getHeader("X-Requested-With");
            if (requestType != null) {
                // 如果requestType不等于空，则表示请求为异步请求，否则为普通请求
                throw new AuthenticationException(USER_NOT_LOGIN);
//                response.getWriter().write("{\"msg\":\"未登录\"}");
            } else {
                response.sendRedirect("/login?redirectURL=" + request.getRequestURL()  + "?" + request.getQueryString());
            }

            return false;
        }
        return true;
    }
}
